package com.zrrd.javaSEPlus._04_reflect;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author WanJl
 * @version 1.0
 * @title ReflectField01
 * @description 通过反射获取Field对象
 * @create 2023/11/12 16:04
 */
public class ReflectField01 {
    /**
     * Field[] getFields()返回所有公共成员变量对象的数组
     */
    public static void method01() throws ClassNotFoundException {
        //1.获取Class对象
        Class<?> clazz = Class.forName("com.zrrd.javaSEPlus._04_reflect.Student");
        //2.获取所有公共的成员变量的对象的数组
        Field[] fields = clazz.getFields();
        System.out.println(Arrays.toString(fields));
    }

    /**
     * Field[] getDeclaredFields()返回所有成员变量对象的数组
     */
    public static void method02(){
        //1.获取Class对象
        Class<Student> clazz = Student.class;
        //2.获取所有成员变量的对象的数组
        Field[] fields = clazz.getDeclaredFields();
        System.out.println(Arrays.toString(fields));
    }

    /**
     * Field getField(String name)返回单个公共成员变量对象
     */
    public static void method03() throws NoSuchFieldException {
        //2.获取Class对象
        Class<? extends Student> clazz = new Student().getClass();
        Field field = clazz.getField("age");
        //age是私有的，会报错NoSuchFieldException
        System.out.println(field);
    }

    /**
     * Field getDeclaredField(String name)返回单个成员变量对象
     */
    public static void method04() throws NoSuchFieldException {
        Class<Student> clazz = Student.class;
        Field field = clazz.getDeclaredField("age");
        System.out.println(field);

    }

    public static void main(String[] args) throws Exception {
        //method01();//成员变量是私有的，所以数组为null
        //method02();
        //method03();
        method04();
    }
}
